# -*- coding: utf-8 -*-

import os
import re
from models import *
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.datastore import entity_pb


def serialize_entities(models):
  if models is None:
    return None
  elif isinstance(models, db.Model):
    # Just one instance
    return db.model_to_protobuf(models).Encode()
  else:
    # A list
    return [db.model_to_protobuf(x).Encode() for x in models]


def deserialize_entities(data):
   if data is None:
     return None
   elif isinstance(data, str):
     # Just one instance
     return db.model_from_protobuf(entity_pb.EntityProto(data))
   else:
     return [db.model_from_protobuf(entity_pb.EntityProto(x)) for x in data]


class LoginControl():
  def CheckLogin(self,role,externalself):
    notlogged = True
    permisiondeny = True
    user = users.get_current_user()
    if str(user)=='None':
      notlogged = True
    else:
      queryuser = CustomUser.all()
      queryuser.filter('user = ',user)
      if queryuser.count()>0:
        notlogged = False
        dbusers = queryuser.fetch(1)
        dbuser = dbusers[0]
        if dbuser.role==role or dbuser.role=='admin':
          permisiondeny = False
          return dbuser.role
        else:
          permisiondeny = True
      else:
        notlogged = True

    if os.environ.has_key('REQUEST_URI'):
      url=str(os.environ['REQUEST_URI'])+"\n\n"
    else:
      url = "http://www.fieltro.org/admin/"

    if notlogged:
      externalself.redirect(users.create_login_url(url))
      return 0

    if permisiondeny:
      externalself.redirect("http://www.fieltro.org")
      return 0

  def CheckAccess(self,role):
    notlogged = False
    permisiondeny = False
    user = users.get_current_user()
    if str(user)=='None':
      notlogged = True
    else:
      queryuser = CustomUser.all()
      queryuser.filter('user = ',user)
      if queryuser.count()>0:
        dbusers = queryuser.fetch(1)
        dbuser = dbusers[0]
        if dbuser.role==role or dbuser.role=='admin':
          return 1
        else:
          permisiondeny = True
      else:
        notlogged = True
     
    if notlogged:
      return 0

    if permisiondeny:
      return 0

class encodingHell():
  def removeEsChars(self, string):
    string = string.replace(u'á', u'a')
    string = string.replace(u'é', u'e')
    string = string.replace(u'í', u'i')
    string = string.replace(u'ó', u'o')
    string = string.replace(u'ú', u'u')
    string = string.replace(u'ñ', u'n')
    string = string.replace(u'ç', u'c')
    string = string.replace(u'"', u"'")
    string = string.replace(u'\n', u'')

    return string


def slugify(string):
    string = re.sub('\s+', '_', string)
    string = re.sub('[^\w.-]', '', string)
    return string.strip('_.- ').lower()